import { Component, OnInit, ViewChild, ElementRef, Output, EventEmitter, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocomplete, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { COMMA, ENTER } from '@angular/cdk/keycodes';

export interface ChipItem {
  id: number | string;
  name: string;
  // ...any other properties
}

@Component({
  selector: 'app-horizontal-chip-group',
  templateUrl: './horizontal-chip-group.component.html',
  styleUrls: ['./horizontal-chip-group.component.scss']
})
export class HorizontalChipGroupComponent implements OnInit {
  @ViewChild('chipInput') chipInput!: ElementRef<HTMLInputElement>;
  @ViewChild('auto') matAutocomplete!: MatAutocomplete;
  @Output() chipsChange = new EventEmitter<ChipItem[]>();
  @Input() allChips: ChipItem[] = [];
  @Input() label: string = '';
  @Input() placeholder: string = '';

  visible = true;
  removable = true;
  addOnBlur = true;
  readonly separatorKeysCodes: number[] = [ENTER, COMMA];
  chipCtrl = new FormControl();
  chips: ChipItem[] = [
    { id: 1, name: 'Angular' },
    { id: 2, name: 'Material' },
    { id: 3, name: 'TypeScript' }
  ];

  constructor() {}

  ngOnInit(): void {}

  add(event: { input: HTMLInputElement, value: string }): void {
    const value = (event.value || '').trim();
    if (value) {
      // Find the chip object in allChips by name
      const found = this.allChips.find(chip => chip.name === value);
      if (found && !this.chips.some(c => c.id === found.id)) {
        this.chips.push(found);
        this.chipsChange.emit([...this.chips]);
        console.log('chipsChange emitted:', this.chips);
      }
    }
    if (event.input) {
      event.input.value = '';
    }
    this.chipCtrl.setValue(null);
  }

  remove(chip: ChipItem): void {
    const index = this.chips.findIndex(c => c.id === chip.id);
    if (index >= 0) {
      this.chips.splice(index, 1);
      this.chipsChange.emit([...this.chips]);
      console.log('chipsChange emitted:', this.chips);
    }
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    const value: ChipItem = event.option.value;
    if (value && !this.chips.some(c => c.id === value.id)) {
      this.chips.push(value);
      this.chipsChange.emit([...this.chips]);
    }
    if (this.chipInput) {
      this.chipInput.nativeElement.value = '';
    }
    this.chipCtrl.setValue(null);
  }

  onChipClick(chip: ChipItem): void {
    // Optional: handle chip click
  }
}
